//
//  BDFillBusinessInfoStep5ViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/13.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "BDFillBusinessInfoStep5ViewController.h"
#import "BDSetBankcardRequest.h"
#import "BDQueryBankcardInfoRequest.h"
#import "UIImage+Tools.h"
#import "BQActivityView.h"
#import "BDCardInformationModel.h"
#import "BDFillBusinessInfoSuccessViewController.h"
#import "BDSelectProvinceViewController.h"
#import "DBSelectBankBranchViewController.h"
#import "BDSelectBankViewController.h"
#import "NSString+Validation.h"

@interface BDFillBusinessInfoStep5ViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *cardNOTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *subBranchTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankAccountName;
@property (weak, nonatomic) IBOutlet UITextField *iDnumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankAddressTextField;

@property (nonatomic, strong) NSString *districtCode;
@property (nonatomic, strong) NSString *branchCode;

@property (weak, nonatomic) IBOutlet UIImageView *selectBankNameRightIcon;

@end

@implementation BDFillBusinessInfoStep5ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.cardNOTextField.delegate = self;
    self.bankAccountName.delegate = self;
    self.subBranchTextField.delegate = self;
    self.bankAccountName.delegate = self;
    self.iDnumberTextField.delegate = self;
    self.bankAddressTextField.delegate = self;
    
    if ((self.model.isPublic  == 1)) {
        self.iDnumberTextField.placeholder = @"法人二代身份证号";
        self.bankNameTextField.placeholder = @"请选择开户行";
    }else{
        self.selectBankNameRightIcon.hidden = YES;
    }
    
    [self.titleButton setTitle:@"店铺资料" forState:UIControlStateNormal];
    if (self.readOnly) {
        [self.rightAreaRBtn setTitle:@"返回" forState:UIControlStateNormal];
    }else{
        [self.rightAreaRBtn setTitle:@"下一步" forState:UIControlStateNormal];
    }
    self.rightAreaRBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [self.rightAreaRBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.rightArea.mas_right);
        make.width.mas_equalTo(@50);
        make.centerY.mas_equalTo(self.rightArea.mas_centerY);
        make.height.mas_equalTo(@30);
    }];

    [self fillbackIfNeed];
}

- (void)fillbackIfNeed{
    if (!self.userShopModel) return;
    self.cardNOTextField.text = self.userShopModel.appBizCard.cardNO;//简称
    self.bankNameTextField.text = self.userShopModel.appBizCard.cardBank; //选择地区
    self.subBranchTextField.text = self.userShopModel.appBizCard.bankAddress; //街道
    self.bankAccountName.text = self.userShopModel.appBizCard.cardAccountName;
    self.iDnumberTextField.text = self.userShopModel.appBizCard.idcardNO;
    self.bankAddressTextField.text = self.userShopModel.appBizCard.branchDistrictName;
    
    self.districtCode = self.userShopModel.appBizCard.branchDistrictCode;
    self.branchCode = self.userShopModel.appBizCard.brankCode;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)handleNavigationAction:(HSYNavigationActionType)actionType{
    if (actionType == HSYNavActionLeftAreaLeft) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if (actionType == HSYNavActionRightAreaRight) {
        [self goNext:nil];
    }
}

- (void)pushToSelectBankName{
    __weak typeof(self) wSelf = self;
    BDSelectBankViewController *vc = [[BDSelectBankViewController alloc] init];
    vc.selectBankBlock = ^(NSString *bankName, NSString *code){
        wSelf.bankNameTextField.text = bankName;
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)selectedBank:(UIButton *)sender{
    if (self.readOnly) return;

    [self.view endEditing:YES];
    if (self.model.isPublic  == 1){ //对公无法自动匹配开户行，只能选择
        [self pushToSelectBankName];
    }
}


//选择分行
- (void)pushToSelectSubBranch{
    DBSelectBankBranchViewController *vc = [[DBSelectBankBranchViewController alloc] init];
    vc.districtCode = self.districtCode;
    vc.bankName = self.bankNameTextField.text;
    
    __weak typeof(self)weakSelf = self;
    vc.selectBankBranchBlock = ^(NSString *branchName, NSString *code){
        weakSelf.subBranchTextField.text = branchName;
        weakSelf.branchCode = code;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)selectedSubBranch:(UIButton *)sender{
    if (self.readOnly) return;

    if ((!self.bankNameTextField.text.length || [self.bankNameTextField.text isEqualToString:@"未识别开户行信息"])) {
        if (self.model.isPublic != 1) {
            [self showMessage:@"未识别开户行信息"];
        }else{
            [self showMessage:@"请选择开户行"];
        }
        return;
    }
    
    if (self.districtCode.length == 0) {
        [self showMessage:@"请选择开户地区"];
        return;
    }
    
    [self pushToSelectSubBranch];
}

//选中城市
- (IBAction)selectProvincesBtnClick:(id)sender {
    if (self.readOnly) return;

    [self.view endEditing:YES];
    
    BDSelectProvinceViewController *vc = [[BDSelectProvinceViewController alloc] init];
    vc.leafCode = 2; //选择到市
    __weak typeof(self)weakSelf = self;
    [vc getProvinceCityCountyinfo:^(NSString *title, NSString *code) {
        weakSelf.bankAddressTextField.text = title;
        weakSelf.districtCode = code;
    }];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)commitData{
    [self.view endEditing:YES];
    
    if (![self checkDataIntegrity]) return;
    
    __weak typeof(self)weakSelf = self;
    [BQActivityView showActiviTy];
    
    BDSetBankcardRequest *task = [[BDSetBankcardRequest alloc] init];
    task.cardNO = self.cardNOTextField.text;
    task.cardBank = self.bankNameTextField.text;
    task.cardAccountName = self.bankAccountName.text;
    task.sid = [NSString stringWithFormat:@"%ld", (long)self.model.shopId];
    task.bankAddress = self.subBranchTextField.text;
    task.idcardNO = self.iDnumberTextField.text;
    task.branchDistrictCode = self.districtCode;
    task.branchCode = self.branchCode;
    
    [BDNetworkManager POST:task completionHander:^(id responseObject, NSString *resultString) {
        [BQActivityView hideActiviTy];
        
        if (responseObject) {
            BDBusinessModel *model = [BDBusinessModel mj_objectWithKeyValues:responseObject];
            weakSelf.model.status = model.status;
            weakSelf.model.auStep = model.auStep;
            //go to next step ,提交成功
            [weakSelf showSuccessViewController];
            
        }else{
            if (resultString) {
                [weakSelf showMessage:resultString];
            }
        }
    }];

}

- (IBAction)goNext:(id)sender {
    [self handleNext];
}



-(BOOL)checkDataIntegrity{
    
    if (!self.bankAccountName.text.length) {
        [self showMessage:@"请输入开户名"];
        return NO;
    }else if (![self.bankAccountName.text isValidPersonName]){
        [self showMessage:@"请输入正确联系人名称"];
        return NO;
    }
    
    if (!self.iDnumberTextField.text.length && (self.model.isPublic == NO)) {
        [self showMessage:@"请输入身份证号"];
        return NO;
    }else if (![self.iDnumberTextField.text isValidIdCard]){
        [self showMessage:@"请输入正确身份证号码"];
        return NO;
    }

    
    if (!self.cardNOTextField.text.length) {
        [self showMessage:@"请输入结算卡卡号"];
        return NO;
    }
    
    if (!self.bankNameTextField.text.length && self.model.isPublic) {
        [self showMessage:@"请选择开户行"];
        return NO;
    }
    
    if ((!self.bankNameTextField.text.length || [self.bankNameTextField.text isEqualToString:@"未识别开户行信息"]) && self.model.isPublic != 1) {
        [self showMessage:@"未识别开户行信息"];
        return NO;
    }
    
    if (self.districtCode.length == 0) {
        [self showMessage:@"请选择开户地区"];
        return NO;
    }
    
    if (!self.subBranchTextField.text.length) {
        [self showMessage:@"请选择支行名称"];
        return NO;
    }
    
    if (!self.branchCode) {
        [self showMessage:@"联行号不能为空"];
        return NO;
    }
    
    return YES;
}

- (void)showSuccessViewController{
    BDFillBusinessInfoSuccessViewController *vc = [[BDFillBusinessInfoSuccessViewController alloc] init];
    vc.model = self.model;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showNotMatchMessage{
    alert_alam(@"", @"您输入的卡号有误或为暂不支持该银行卡。");
}

- (void)retryMatchBankIfNeed{
    static NSInteger retryTime = 0;
    
    if (retryTime > 3) return; //如果请求失败， 重试3次
    retryTime ++;
    
    [self matchBankNameWithBankCode:self.cardNOTextField.text];
}

- (void)matchBankNameWithBankCode:(NSString *)code{
    __weak typeof(self)weakSelf = self;
    
    BDQueryBankcardInfoRequest *task = [[BDQueryBankcardInfoRequest alloc] init];
    task.cardNO = code;
    
    [BDNetworkManager POST:task completionHander:^(id responseObject, NSString *resultString) {
        if (responseObject) {
            BDCardInformationModel *model = [BDCardInformationModel mj_objectWithKeyValues:responseObject];
            if (model.bankName.length > 0) {
                weakSelf.bankNameTextField.text = model.bankName;
                weakSelf.bankNameTextField.textColor = [UIColor blackColor];
            }else{
                weakSelf.bankNameTextField.text = @"未识别开户行信息";
                weakSelf.bankNameTextField.textColor = [UIColor redColor];
                
                [weakSelf performSelector:@selector(showNotMatchMessage) withObject:nil afterDelay:0.5];
                //                [weakSelf showNotMatchMessage];
            }
        }else{
            if (resultString) {
                [weakSelf retryMatchBankIfNeed];
            }
        }
    }];

}

#pragma mark UITextFieldDelegate


-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField == self.cardNOTextField && textField.text.length > 0 && self.model.isPublic != 1) {
        [textField resignFirstResponder];
        [self matchBankNameWithBankCode:textField.text];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    return YES;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
